package com.koylu.faces.component.text;

import javax.faces.application.FacesMessage;
import javax.faces.component.html.HtmlInputText;
import javax.faces.context.FacesContext;
import javax.faces.el.EvaluationException;
import javax.faces.el.MethodBinding;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

public class JSFInputText extends HtmlInputText {	
	
	protected void validateValue(FacesContext context, Object convertedValue) {
		Validator[] validators = this.getValidators();
		for (int i = 0; i < validators.length; i++) {
			Validator validator = validators[i];
			try {
				validator.validate(context, this, convertedValue);
			} catch (ValidatorException e) {
				this.setValid(false);
				FacesMessage facesMessage = e.getFacesMessage();
				if (facesMessage != null) {
					facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
					context.addMessage(this.getClientId(context), facesMessage);
				}
				break;			
			}
		}
		MethodBinding validatorBinding = this.getValidator();
		if (validatorBinding != null) {
			try {
				validatorBinding.invoke(context, new Object[] { context, this, convertedValue });
			} catch (EvaluationException e) {
				this.setValid(false);
				Throwable cause = e.getCause();
				if (cause instanceof ValidatorException) {
					FacesMessage facesMessage = ((ValidatorException) cause).getFacesMessage();
					if (facesMessage != null) {
						facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
						context.addMessage(this.getClientId(context),facesMessage);
					}
				} else {
					throw e;
				}
			}
		}
	}
}
